package com.platformer.screens;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.TimeUtils;
import com.platformer.controller.HeroController;
import com.platformer.levels.Level;
import com.platformer.model.Ground;
import com.platformer.model.Hero;
import com.platformer.view.HeroRenderer;

public class GamePlayScreen extends AbstractScreen {

	private World world;
	private Level currentLevel;
	private Hero hero;
	private HeroRenderer heroRenderer;
	private HeroController heroController;
	private Box2DDebugRenderer debugRenderer;
	private OrthographicCamera camera;
	private BitmapFont font;
	

	public GamePlayScreen(Game game) {
		super(game);

		world = new World(new Vector2(0, -10), true);
		
		currentLevel = new Level(world);
		hero = new Hero(world);
		heroRenderer = new HeroRenderer(hero);
		heroController = new HeroController(hero, heroRenderer);
		debugRenderer = new Box2DDebugRenderer();

//		camera = new OrthographicCamera(48, 32);
//		camera.position.set(0, 16, 0);
		camera = new OrthographicCamera();
		camera.setToOrtho(false, 30, 20);
		
		font = new BitmapFont(Gdx.files.internal("data/arial-15.fnt"), false);
		font.setColor(Color.WHITE);

		Gdx.input.setInputProcessor(heroController);	
	}

	@Override
	public void render(float delta) {
		super.render(delta);

		long startTime = TimeUtils.nanoTime();
		world.step(1 / 45f, 8, 3);
		float updateTime = (TimeUtils.nanoTime() - startTime) / 1000000000.0f;

		heroController.update(delta);

		// Gdx.gl.glClearColor(0, 0, 0, 0);
		Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
		camera.update();

		// set the projection matrix of the
		// SpriteBatch to the camera's combined matrix. This will
		// make the SpriteBatch work in world coordinates
		batch.getProjectionMatrix().set(camera.combined);
		batch.begin();
		heroRenderer.render(delta, batch, camera);		
		batch.end();

		debugRenderer.render(world, camera.combined);
		
		currentLevel.render(camera);

		// finally we render the time it took to update the world
		// for this we have to set the projection matrix again, so
		// we work in pixel coordinates
		batch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(),
				Gdx.graphics.getHeight());
		batch.begin();
		font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond()
				+ " update time: " + updateTime, 0, 20);
		batch.end();
	}
	
}
